package com.exchange.service.impl;

import com.exchange.service.JobService;
import com.exchange.utils.result.CommonResult;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class JobServiceImpl implements JobService {


    @Override
    public CommonResult execRepositoryJobs(KettleDatabaseRepository repository, String jobName) throws KettleException {
        //根据变量查找到模型所在的目录对象,此步骤很重要。
        RepositoryDirectoryInterface directory = repository.findDirectory("/");
        //创建kjb元对象
        JobMeta jobMeta = ((Repository) repository).loadJob(jobName, directory, null, null);
        //创建kjb
        Job job = new Job(repository, jobMeta);
        job.setVariable("id", UUID.randomUUID().toString());
        //启动作业
        job.start();
        //等待作业执行完成
        job.waitUntilFinished();
        if (job.getErrors() > 0) {
            return CommonResult.fail("作业执行失败");
        } else {
            return CommonResult.success("作业执行成功");
        }
    }
}
